import HTTP_METHOD from '../constant/httpMethod'
import HTTP_STATUS_CODE from 'http-status-codes'

export const post = async (url, user) => {
    try {
        const res = await fetch(url, {
            method: HTTP_METHOD.POST,
            credentials: 'include',
            headers: new Headers({
                'Content-Type': 'application/json;charset=utf-8',
                'Accept': 'application/json'
            }),
            body: JSON.stringify(user)
        })

        const status = res.status
        if (status !== HTTP_STATUS_CODE.CREATED) {
            const body = await res.json()
            return Object.assign({}, {body}, {status})
        }
        return {status}
    } catch (ex) {
        alert(ex)
    }
}

export const update = async (url, growthNote) => {
    try {
        const res = await fetch(url, {
            method: HTTP_METHOD.PUT,
            credentials: 'include',
            headers: new Headers({
                'Content-Type': 'application/json;charset=utf-8',
                'Accept': 'application/json'
            }),
            body: JSON.stringify(growthNote)
        })
        const status = res.status
        if (status !== HTTP_STATUS_CODE.NO_CONTENT) {
            const body = await res.json()
            return Object.assign({}, {body}, {status})
        }
        return {status}
    } catch (ex) {
        alert(ex)
        return {status: ex.status}
    }
}

export const get = async (url) => {
    try {
        const res = await fetch(url, {
            method: HTTP_METHOD.GET,
            credentials: 'include',
            headers: new Headers({
                'Content-Type': 'application/json;charset=utf-8',
                'Accept': 'application/json'
            })
        })
        const status = res.status
        if (res.ok) {
            const body = await res.json()
            return Object.assign({}, {body}, {status})
        }
        return {status}
    } catch (ex) {
        alert(ex)
        return {status: ex.status}
    }
}
